# encoding: utf-8

import os
import sys
import csv
import glob

from dbfpy import dbf


def dbf_to_csv(file_name):
    csv_dir, csv_file_name = os.path.split(file_name)
    csv_file = csv_dir + os.sep + os.path.splitext(csv_file_name)[0] + ".csv"
    writer = csv.writer(open(csv_file, "wb"))  # w文件删除重建 b以二进制方式
    db = dbf.Dbf(csv_file)
    writer.writerow(db.fieldNames)
    [writer.writerow(record.fieldData) for record in db]

if __name__ == '__main__':
    dir_name = "..\dbf\*.zip"
    for file_name in glob.glob(dir_name):
        os.system("unzip -o -d ", os.path._getfullpathname(file_name))

    dir_name = "..\dbf\*.dbf"
    for file_name in glob.glob(dir_name):
        dbf_to_csv(file_name)
